package snapex.expense.service.impl;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.web.client.RestTemplate;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

import lombok.extern.slf4j.Slf4j;
import snapex.core.model.Result;
import snapex.core.model.SearchParams;

@Slf4j
@Service
public class ExpenseServiceProxy {
	
	@Autowired
	private RestTemplate restTemplate;
	
	@Value("${snapex.expenseClient.expenseDataUrl}")
	String expenseDataUrl;
	
	@Value("${snapex.expenseClient.oauthTokenUrl}")
	String oauthTokenUrl;
		
	@Value("${snapex.expenseClient.clientId}")
	String clientId;
	
	@Value("${snapex.expenseClient.clientSecret}")
	String clientSecret;
			
	@HystrixCommand(commandKey="expense-service-exportall" ,groupKey="expense-service",threadPoolKey="expense-service",fallbackMethod = "getExpensesFallback")
	public byte[] exportAll(SearchParams params){
		
		HttpHeaders requestHeaders = new HttpHeaders();
		requestHeaders.add(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString((clientId+":"+clientSecret).getBytes()));
		
		HttpEntity requestEntity = new HttpEntity(null, requestHeaders);
				
		Map token = restTemplate.exchange(oauthTokenUrl,HttpMethod.POST, requestEntity, Map.class).getBody();
		
//		log.debug("******token:{}",token.get("access_token"));
			
		requestHeaders = new HttpHeaders();
		requestHeaders.add(HttpHeaders.AUTHORIZATION, "Bearer " + token.get("access_token"));	
		
		requestHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
		
		requestEntity = new HttpEntity<SearchParams>(params, requestHeaders);
		
		return restTemplate.exchange(expenseDataUrl, HttpMethod.POST, requestEntity, byte[].class).getBody();
	}
	
	@SuppressWarnings("unused")
	private Result exportAll(SearchParams condition, Throwable t) {
		
		log.error("Error",t);
		
		return Result.failure().msg("Failed to export records");
	}
}
